package rabbitMQ.simple;

import com.rabbitmq.client.*;
import rabbitMQ.common.Common;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Common.HOST);//ip
        factory.setPort(Common.PORT);//端口号
        factory.setVirtualHost(Common.VIRTUALHOST);//虚拟机名称
        factory.setUsername(Common.USERNAME);//用户名
        factory.setPassword(Common.PASSWORD);//密码
        //3. 创建连接connection
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(Common.SIMPLE_QUEUE, true, false, false, null);
        //消费消息
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("获取到队列: " + new String(body));
            }
        };
        //消费消息
        channel.basicConsume(Common.SIMPLE_QUEUE, true, consumer);

        Thread.sleep(2000);
        //释放资源
        channel.close();
        connection.close();
    }
}
